package com.dk.pair;

import com.dk.util.DataMark;
import com.dk.util.RFIDUtil;
import gnu.io.*;

import java.io.IOException;
import java.util.*;


public class Callable1 {

    static StringBuffer sb = new StringBuffer();
    static Set<String> resultList = new LinkedHashSet<String>();
    List<SerialPort> available = new ArrayList<SerialPort>();
    //获取串口实体
    public  List<SerialPort> getSerialPort(){
        SerialPort port = null;
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
        ArrayList<String> portNameList = new ArrayList<String>();
        //List<SerialPort> list = new ArrayList<SerialPort>();
        while (portList.hasMoreElements()){
            String portName = portList.nextElement().getName();
            System.out.println();
            portNameList.add(portName);
            System.out.println(portName);
        }
        for (String portNameStr :portNameList){
            try {
                port = RFIDUtil.openPort(portNameStr,115200);
                available.add(port);
            } catch (PortInUseException e) {
                e.printStackTrace();
            } catch (NoSuchPortException e) {
                e.printStackTrace();
            }
        }
        return available;
    }
    //打开并获取获取串口连接状态
    public boolean getDeviceStatus(){
        getSerialPort();
        if (available.size()<1){
            return false;
        }else {
            return true;
        }
    }
    //获取串口数据
    public Set<String> getDeviceData(){
        List<Byte> mbList = new ArrayList<Byte>();
        DataMark mDataMark = null;
        //List<SerialPort> list = getSerialPort();
        for (SerialPort port:available){
            int index = 0;
            byte[] byteStr = RFIDUtil.setNextAnt();
            byte[] data = null;
            byte[] command = RFIDUtil.readCommand();
            String curTag = "";
            System.out.print("controllCommand:");
            System.out.println();
            System.out.print("readCommand:");
            System.out.println();
            //RFIDUtil.addListener(port,new SerialPortPort1(port));
            boolean flag = true;
            resultList.clear();
            while (flag){
                index ++ ;
                RFIDUtil.sendToPort(port,command);
                RFIDUtil.sendToPort(port,byteStr);
                mDataMark = findNextDataMark(mbList);
                try {
                    data = RFIDUtil.readFromPort(port);
                    if (data != null && mDataMark != null ){
                        //System.out.println("未处理的数据："+RFIDUtil.byteToString(data)+"  ");
                        for (Byte by:data){
                            mbList.add(by);
                        }
                        if(mDataMark != null && mDataMark.isTag){

                            curTag = RFIDUtil.praseTag(mbList,mDataMark);
                            if (curTag != null && mDataMark.isTag){
                                if (curTag.length() > 10){
                                    resultList.add(curTag);
                                }
                            }
                            //清除本次所读取的数据
                            mbList.clear();
                        }

                    }
                    if (index >3000){
                        flag = false;
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            port.close();
        }
        return  resultList;
    }
    public DataMark findNextDataMark(List<Byte> mbList) {

        synchronized (mbList) {

            ////CHLog.d(TAG, "going to find mark");
            int end = 0;
            DataMark mDataMark = new DataMark();
            for(int i = 0; i < mbList.size(); i++ ) {

                if(mbList.get(i) == (byte)0xA0) {

                    end = findEndIndex(mbList,i);
                    if(end != -1) {
                        mDataMark.setStart(i);
                        mDataMark.setEnd(end);
                        if(mbList.get(i+1) == 0x04) {

                            mDataMark.setTag(false);
                        }else {
                            mDataMark.setTag(true);
                        }
                        ////CHLog.d(TAG, "mark start ="+i+ "  mark end = "+end);
                    }
                }
            }
            return mDataMark;
        }

    }
    private int findEndIndex(List<Byte> mbList,int index) {

        if(index+1 >= mbList.size() || mbList.get(index) != (byte)0xA0){

            return -1;
        }

        int len = RFIDUtil.byteToInt(mbList.get(index+1));
        int end = index+1+len;
        if(end > mbList.size()-1){

            return -1;
        }
        byte crc = mbList.get(end);
        byte cal_crc = RFIDUtil.CheckSum(mbList, index, end-1);
        if(crc != cal_crc) {

            return -1;
        }
        return end;
    }

   /* //加入监听
    private static class SerialPortPort1 implements SerialPortEventListener{

        public SerialPort serialPort1;

        public SerialPortPort1( SerialPort serialPort1 ) {
            this.serialPort1 = serialPort1;
        }

        public void serialEvent( SerialPortEvent serialPortEvent) {
            // TODO Auto-generated method stub
            switch (serialPortEvent.getEventType()) {

                case SerialPortEvent.BI: // 10 通讯中断
                    break;

                case SerialPortEvent.OE: // 7 溢位（溢出）错误

                case SerialPortEvent.FE: // 9 帧错误

                case SerialPortEvent.PE: // 8 奇偶校验错误

                case SerialPortEvent.CD: // 6 载波检测

                case SerialPortEvent.CTS: // 3 清除待发送数据

                case SerialPortEvent.DSR: // 4 待发送数据准备好了

                case SerialPortEvent.RI: // 5 振铃指示

                case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2 输出缓冲区已清空
                    break;

                case SerialPortEvent.DATA_AVAILABLE: // 1 串口存在可用数据

                    byte[] data = null;

                    try {
                        if (serialPort1 == null) {

                        }
                        else {
                            data = RFIDUtil.readFromPort(serialPort1);    //读取数据，存入字节数组
//	                    System.out.println(new String(data,"GBK"));
                            String str = RFIDUtil.byteToString(data);
//	                    System.out.println(str);
                            sb.append(str);

                            if(sb.length()==72){
                                final String rfidData = sb.toString();
                                sb.setLength(0);
                                out.println(rfidData);
                                if("0112".equals(rfidData.substring(0,4))){
                                    new Thread(new Runnable() {

                                        public void run() {
                                            // TODO Auto-generated method stub
                                        }
                                    }).start();

                                }
                            }
                            if(sb.length()>72){
                                sb.setLength(0);
                            }

                        }
                    } catch (Exception e) {
                        //   exit(0);    //发生读取错误时显示错误信息后退出系统
                        // e.printStackTrace();
                    }
                    break;
            }


        }

    }*/

}
